package com.asen.libcommon.base

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.asen.libcommon.base.viewbind.BaseViewModel
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import io.reactivex.disposables.CompositeDisposable


/**
 *    @author : asenLiang
 *    @date   : 2020/12/3
 *    @desc   : 滑动返回基类封装,根據该基类拓展基类
 */
abstract class BaseActivity(
    /** rxJava 綁定 使用addDispose方法加入创建的rxJava,在销毁的时候统一处理防止内存泄漏*/
    internal var compositeDisposable: CompositeDisposable? = null
) : AppCompatActivity() {

    // TODO: viewModel绑定类
    open val mViewModel: BaseViewModel? = null

    private var mLoadToast: LoadingPopupView? = null

    protected fun initToast() {
        mViewModel?.apply {
            LOADING.extObserver {

                if (it == null){
                    mLoadToast?.dismiss()
                    return@extObserver
                }

                // 是否显示
                if (it!!.isShow) {
                    if (mLoadToast == null) {
                        mLoadToast = XPopup.Builder(this@BaseActivity)
                            .dismissOnBackPressed(false)
                            .isLightNavigationBar(true)
                            .isViewMode(true)
                            .asLoading("加载中")
                            .setTitle(it.msg ?: "")
                            .show() as LoadingPopupView
                    }
                } else {
                    //mLoadToast?.smartDismiss()
                    mLoadToast?.dismiss()
                }
            }
        }
    }


    /**
     * Activity中，快速实现MutableLiveData观察方法
     * 默认使用的生命周期所有者为当前activity
     */
    protected fun <T> MutableLiveData<T>.extObserver(
        owner: LifecycleOwner = this@BaseActivity,
        callback: (T?) -> Unit
    ) {
        this.observe(owner, Observer { callback.invoke(it) })
    }

    override fun onDestroy() {
        mLoadToast?.dismiss()
        super.onDestroy()
    }

}